package com.steven.ourcontest.chat.view

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.chat.adapter.TeamViewBinder
import com.steven.ourcontest.chat.viewmodel.UserDetailViewModel
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.me.widget.GlideRoundTransform
import com.steven.ourcontest.net.NetConstants
import com.steven.ourcontest.team.bean.TeamInfo
import com.steven.ourcontest.utils.Identity
import com.steven.ourcontest.utils.toast
import com.zyyoona7.popup.EasyPopup
import com.zyyoona7.popup.XGravity
import com.zyyoona7.popup.YGravity
import kotlinx.android.synthetic.main.activity_user_detail.*
import kotlinx.android.synthetic.main.activity_user_detail.iv_icon
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter

class UserDetailActivity : BaseActivity(isImmersed = true) {

    private val userDetailViewModel: UserDetailViewModel by viewModels()
    private var uid: Long = 0
    private val adapter by lazy {
        MultiTypeAdapter(item)
    }
    private val item = Items()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initListener()
    }

    override fun getViewId(): Int? {
        return R.layout.activity_user_detail
    }

    override fun initView() {
        uid = intent.getLongExtra("uid", 0)
        if (uid == 0L) {
            finish()
            return
        }
        rv_team?.adapter = adapter
        adapter.register(TeamInfo::class.java, TeamViewBinder(this) {
            userDetailViewModel.applyToTeam(it, {
                toast("申请成功！")
            }, { error ->
                toast(error)
            })
        })
        iv_more?.apply {
            iv_more?.setOnClickListener {
                val popupWindow = EasyPopup.create()
                    .setContentView(this@UserDetailActivity, R.layout.menu_user_detail)
                    .setAnimationStyle(R.style.PopupAnimation)
                    .setFocusAndOutsideEnable(true)
                    .apply()
                popupWindow.showAtAnchorView(this, YGravity.BELOW, XGravity.ALIGN_LEFT, 0, 0)
                val report = popupWindow.findViewById<TextView>(R.id.tv_report)
                val addBan = popupWindow.findViewById<TextView>(R.id.tv_add_ban)
                val deleteBan = popupWindow.findViewById<TextView>(R.id.tv_delete_ban)
                report?.setOnClickListener reportClick@{
                    if (!LoginController.isLogin) {
                        toast("请先登录")
                        return@reportClick
                    }
                    if (LoginController.userType == "") {
                        toast("账户尚未通过身份认证！")
                        return@reportClick
                    }
                    AppRouter.openReportActivity(this@UserDetailActivity, uid)
                }
                if (LoginController.userType == Identity.ADMIN.value) {
                    addBan?.isVisible = true
                    deleteBan?.isVisible = true
                    addBan?.setOnClickListener {
                        userDetailViewModel.addBan(uid, {
                            toast("封禁成功！")
                            popupWindow.dismiss()
                        }, {
                            toast(it)
                        })
                    }
                    deleteBan?.setOnClickListener {
                        userDetailViewModel.deleteBan(uid, {
                            toast("解封成功！")
                            popupWindow.dismiss()
                        }, {
                            toast(it)
                        })
                    }
                }
            }
        }
    }

    private fun initListener() {
        userDetailViewModel.userDetailResponse.observe(this, Observer {
            it?.data?.let { data ->
                tv_name?.text = data.uname
                tv_school_name?.text = data.school
                tv_college_name?.text = data.college
                data.judge?.let { judge ->
                    tv_judge_name?.text = judge
                }
                data.iconUrl?.let { icon ->
                    Glide.with(this)
                        .load(NetConstants.ICON_BASE_URL + icon)
                        .error(R.drawable.ic_avatar)
                        .apply(RequestOptions.bitmapTransform(GlideRoundTransform(this, 40)))
                        .into(iv_icon)
                    Glide.with(this)
                        .load(NetConstants.ICON_BASE_URL + icon)
                        .error(R.drawable.ic_avatar)
                        .into(iv_big_icon)
                }
                tv_chat?.setOnClickListener {
                    if (!LoginController.isLogin) {
                        toast("请先登录")
                        return@setOnClickListener
                    }
                    if (LoginController.userType == "") {
                        toast("账户尚未通过身份认证！")
                        return@setOnClickListener
                    }
                    AppRouter.startChatActivity(this, uid, data.uname)
                }
                tv_add_friend?.setOnClickListener {
                    if (!LoginController.isLogin) {
                        toast("请先登录")
                        return@setOnClickListener
                    }
                    if (LoginController.userType == "") {
                        toast("账户尚未通过身份认证！")
                        return@setOnClickListener
                    }
                    userDetailViewModel.sendApplyToFriend(uid) {
                        toast("已发送申请！")
                    }
                }
            }
            tv_add_friend?.isVisible = it.isFriend == false
            if (tv_add_friend?.isVisible == true) {
                rv_team?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                        super.onScrollStateChanged(recyclerView, newState)
                        if (!recyclerView.canScrollVertically(-1)) {
                            tv_chat?.isVisible = true
                            tv_chat?.alpha = 1f
                            tv_add_friend?.isVisible = true
                            tv_add_friend?.alpha = 1f
                        }
                    }

                    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                        super.onScrolled(recyclerView, dx, dy)
                        changeViewAlpha(tv_add_friend, recyclerView)
                        changeViewAlpha(tv_chat, recyclerView)
                    }
                })
            } else {
                rv_team?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                        super.onScrollStateChanged(recyclerView, newState)
                        if (!recyclerView.canScrollVertically(-1)) {
                            tv_chat?.isVisible = true
                            tv_chat?.alpha = 1f
                        }
                    }

                    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                        super.onScrolled(recyclerView, dx, dy)
                        changeViewAlpha(tv_chat, recyclerView)
                    }
                })
            }

        })
        userDetailViewModel.userTeamResponse.observe(this, Observer {
            item.clear()
            item.addAll(it.data)
            adapter.notifyDataSetChanged()
        })
    }

    override fun onResume() {
        super.onResume()
        userDetailViewModel.queryUserDetail(uid)
        userDetailViewModel.queryUserTeam(uid)
    }

    private val sStartY = 100
    private val sEndY = 400
    private fun changeViewAlpha(view: View?, recyclerView: RecyclerView) {
        val scrollY = recyclerView.computeVerticalScrollOffset()
        if (view?.isVisible == true) {
            if (scrollY in sStartY..sEndY) {
                view.alpha = 1 - ((scrollY - sStartY) / (sEndY - sStartY).toFloat())
            }
            if (scrollY >= sEndY) {
                view.isVisible = false
            }
            if (!recyclerView.canScrollVertically(1)) {
                view.isVisible = false
            }
        } else if (view?.isVisible == false) {
            if (scrollY in sStartY..sEndY) {
                view.isVisible = view.isVisible == false
                view.alpha = 1 - ((scrollY - sStartY) / (sEndY - sStartY).toFloat())
            }
            if (scrollY <= sStartY) {
                view.alpha = 1f
                view.isVisible = true
            }
        }
    }
}